import Koa from 'koa';
import Router from 'koa-router';
import axios from 'axios';
import qs from 'querystring';
import serve from 'koa-static';
import { githubAuthConfig } from './config.js';
import { githubAccessTokenURL, githubAuthBaseURL } from './urls.js';

const { clientId, clientSecret } = githubAuthConfig;

const app = new Koa();
const router = new Router();

app.use(serve('.'));

router.get('/github/login', async ctx => {
    const path = `${githubAuthBaseURL}?client_id=${clientId}`;
    ctx.redirect(path);
});

router.get('/auth/github/callback', async ctx => {
    const { code } = ctx.query;

    const res = await axios.post(githubAccessTokenURL, {
        client_id: clientId,
        client_secret: clientSecret,
        code
    });

    const { access_token } = qs.parse(res.data);
    
    const userRes = await axios.get('https://api.github.com/user', {
        headers: {
            accept: 'application/json',
            Authorization: `token ${access_token}`
        }
    });
    
    ctx.body = `
        <h1>hello, ${userRes.data.name}<h1>
        <img src='${userRes.data.avatar_url}' width='100' height='100' />
    `;
});

app.use(router.routes());
app.listen(7001, () => {
    console.info('app is already start on 7001');
});